/**
 * 
 */
package com.wubo.sec.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Service;

import com.wubo.sec.bean.UserGroupRelate;
import com.wubo.sec.config.LangUtil;
import com.wubo.sec.event.GroupEvent;
import com.wubo.sec.log.LogHelper;
import com.wubo.sec.log.LogState;
import com.wubo.sec.model.Group;
import com.wubo.sec.model.User;
import com.wubo.sec.service.IUserGroupService;
import com.wubo.spring.hibernate.BaseHibernateDao;

/**
 * @author wubo
 * @CreateDate 2010-8-9
 * @version 1.0.01
 */
@Service
public class UserGroupService implements IUserGroupService, ApplicationListener<ApplicationEvent> {
	
	private BaseHibernateDao dao;
	
	public BaseHibernateDao getDao() {
		return dao;
	}
	@Autowired
	public void setDao(BaseHibernateDao dao) {
		this.dao = dao;
	}
	
	public String getGroupCode(String username) {
		return dao.queryForObject("select g.code from User u inner join u.group g where u.username = ?", new Object[]{username});
	}

	public void relate(UserGroupRelate relate) {
		String username = relate.getUsername();
		String groupCode = relate.getGroupCode();
		
		User user = dao.get(User.class, username);
		
		if(groupCode != null){
			Group group = dao.get(Group.class, groupCode);
			user.setGroup(group);
		}else{
			user.setGroup(Group.DEFAULT_GROUP);
		}
		
		dao.update(user);
		
		Group temp = user.getGroup();

		if(LogState.isLogCode()){
			LogHelper.actionLog(LangUtil.get("RelateUserGroup"), LangUtil.get("UserGroupDetail", username+"("+user.getUserText()+")", temp.getCode()+"("+temp.getName()+")"));
		}else{
			LogHelper.actionLog(LangUtil.get("RelateUserGroup"), LangUtil.get("UserGroupDetail", user.getUserText(), temp.getName()));
		}
		
		
	}
	
	public void onApplicationEvent(ApplicationEvent event) {
		if(event instanceof GroupEvent){
			GroupEvent groupEvent = (GroupEvent) event;
			if(groupEvent.getType() == GroupEvent.DELETE){
				dao.executeSQL("UPDATE SEC_USER SET GROUP_REL = ? WHERE GROUP_REL = ?"
						, new Object[]{null, groupEvent.getEntity().getCode()});
			}
		}
	}

}
